package com.leo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.*;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * @ClassName DraggedCopyDemo
 * @Description
 * @Author wangss
 * @date 2020.06.05 14:12
 * @Version 1.0
 */
public class DraggedCopyDemo2 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(an);

        HBox hBox = new HBox(30d);
        hBox.setStyle("-fx-background-color: #fff2f2");
        hBox.setPrefWidth(300d);
        hBox.setPrefHeight(300d);

        ImageView iv = new ImageView();
        iv.setPreserveRatio(true);
        iv.setFitWidth(300d);
        iv.setFitHeight(300d);

        hBox.getChildren().add(iv);

        AnchorPane.setTopAnchor(hBox, 100d);
        AnchorPane.setLeftAnchor(hBox, 100d);

        an.getChildren().addAll(hBox);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ImageViewDemo");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
        primaryStage.setResizable(false);
        primaryStage.show();

        hBox.setOnDragEntered(event -> {
            // 进入时显示一个边框
            hBox.setBorder(new Border(new BorderStroke(Paint.valueOf("#FF845D"), BorderStrokeStyle.SOLID, new CornerRadii(2), new BorderWidths(2))));
        });

        hBox.setOnDragExited(event -> {
            hBox.setBorder(null);
        });

        hBox.setOnDragOver(event -> {
            event.acceptTransferModes(TransferMode.COPY);

        });

        hBox.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();

            if (db.hasFiles()) {
                List<File> files = db.getFiles();

                Image image = null;
                try {
                    image = new Image(new FileInputStream(files.get(0)));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                iv.setImage(image);
            } else if (db.hasUrl()) {
                Image image = new Image(db.getUrl());
                iv.setImage(image);
            }

        });

    }
}
